﻿function UserGeolocation() {
    var _latitude, _longitude;
    function _save2db() {
        alert("User latitude: " + _latitude);
        alert("User longitude: " + _longitude);
        //TO DO: 1-save lat,longt with userpart.
        //or 2-search the nearby locations around this lat,longt by Lucene.net ,but i notice spatial.net has not been completed.
        //$.post(UserGeolocation.url, { latitude: _latitude, longitude: _longitude });      
       
    }
    this.get_latitude = function () {
        return _latitude;
    }
    this.set_latitude = function (latitude) {
        _latitude = latitude;
    }
    this.get_longitude = function () {
        return _longitude;
    }
    this.set_longitude = function (longitude) {
        _longitude = longitude;
    }
    this.save2db = _save2db;
    this.getCurrentLocationByIpAddress = function () {
         if (UserGeolocation.ipInfoDbKey != '') {
             // alert("ipInfoDbKey:" + UserGeolocation.ipInfoDbKey);
            var visitorGeolocation = new geolocate(false, true, UserGeolocation.ipInfoDbKey);           
            var callback = function () {               
//                alert('Visitor country code : ' + visitorGeolocation.getField('countryCode'));
//                alert('Visitor city code : ' + visitorGeolocation.getField('cityName'));
//                alert('Visitor latitude : ' + visitorGeolocation.getField('latitude'));
//                alert('Visitor longitude : ' + visitorGeolocation.getField('longitude'));
                try {
                _latitude = visitorGeolocation.getField('latitude');
                _longitude = visitorGeolocation.getField('longitude');
                _save2db();
                } catch (e) {
                    alert(e);
                }
            };
            visitorGeolocation.checkcookie(callback);
        }
    }
}
UserGeolocation.ipInfoDbKey = '';
UserGeolocation.url = '';
//IPInfoDB jQuery JSON query example FROM IPINFODB.COM
//Tested with FF 3.5, Opera 10, Chome 5 and IE 8
//Geolocation data is stored as serialized JSON in a cookie
//Bug reports : http://forum.ipinfodb.com/viewforum.php?f=7
function geolocate(timezone, cityPrecision,key) {
    //var key = '';
    var api = (cityPrecision) ? "ip-city" : "ip-country";
    var domain = 'api.ipinfodb.com';
    var version = 'v3';
    var url = "http://" + domain + "/" + version + "/" + api + "/?key=" + key + "&format=json" + "&callback=?";
    var geodata;
    var JSON = JSON || {};

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        } else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof (v);
                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };

    //Check if cookie already exist. If not, query IPInfoDB
    this.checkcookie = function (callback) {
        geolocationCookie = getCookie('geolocation');
        if (!geolocationCookie) {
            getGeolocation(callback);
        } else {
            geodata = JSON.parse(geolocationCookie);
            callback();
        }
    }

    //Return a geolocation field
    this.getField = function (field) {
        try {
            return geodata[field];
        } catch (err) { }
    }

    //Request to IPInfoDB
    function getGeolocation(callback) {
        try {
            $.getJSON(url,
      function (data) {
          if (data['statusCode'] == 'OK') {
              geodata = data;
              JSONString = JSON.stringify(geodata);
              setCookie('geolocation', JSONString, 365);
              callback();
          }
      });
        } catch (err) { }
    }

    //Set the cookie
    function setCookie(c_name, value, expire) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expire);
        document.cookie = c_name + "=" + escape(value) + ((expire == null) ? "" : ";expires=" + exdate.toGMTString());
    }

    //Get the cookie content
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return '';
    }
}


